package sun.it.web;

import org.apache.commons.beanutils.BeanUtils;
import sun.it.domain.User;
import sun.it.service.UserService;
import sun.it.service.impl.UserServiceimpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/userLoginServlet")
public class UserLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Map<String, String[]> parm = request.getParameterMap();
        User user=new User(username,password);
        try {
            BeanUtils.populate(user,parm);
        } catch (IllegalAccessException e) {

        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        UserService service=new UserServiceimpl();
        User users = service.CheckLogin(user);
        if(users!=null){
            session.setAttribute("user",user);
            session.setAttribute("username",user.getUsername());
            request.getRequestDispatcher("index.jsp").forward(request,response);
           //response.sendRedirect(request.getContextPath()+"/index.html");
        }else{
            request.setAttribute("error_msg","账号或密码错误!");
            request.getRequestDispatcher("login.jsp").forward(request,response);

            //response.sendRedirect(request.getContextPath()+"/login.html");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
    }
}
